package hust.rpc.client;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用来保存已发送但尚未收到恢复的请求
 */
public class UnprocessedRequests {

    private static volatile UnprocessedRequests unprocessedRequests;

    private static final Map<String , CompletableFuture<String>> UNPROCESSED_RESPONSE_FUTURES = new ConcurrentHashMap<>();

    private UnprocessedRequests(){

    }


    public static UnprocessedRequests getUnprocessedRequests(){
        if (unprocessedRequests == null){
            synchronized (UnprocessedRequests.class){
                if (unprocessedRequests == null){
                    unprocessedRequests = new UnprocessedRequests();
                }
            }
        }
        return unprocessedRequests;
    }

    public void put(String requestId , CompletableFuture<String> future){

        UNPROCESSED_RESPONSE_FUTURES.put(requestId,future);
    }

    public void complete(String requestId , String result){
        CompletableFuture<String> future = UNPROCESSED_RESPONSE_FUTURES.remove(requestId);

        if (null != future){
            future.complete(result);
        }else {
            throw new IllegalStateException();
        }
    }

}
